//
//  ECMaterailTypeListViewController.m
//  ECERP.CRM
//
//  Created by huanggulong on 2018/11/22.
//  Copyright © 2018 Mac. All rights reserved.
//

#import "ECMaterailTypeListViewController.h"
#import "ECMaterailTypeEditViewController.h"
#import "ECMaterialTypeBigTypeHeaderView.h"
#import "GLBaseHTTPTool.h"
#import "ECShopMaterialType.h"

@interface ECMaterailTypeListViewController ()<UITableViewDelegate,UITableViewDataSource,ECMaterialTypeBigTypeHeaderViewDelegate>

@property (nonatomic,strong) UITableView * tableView;

@property (nonatomic,strong) NSMutableArray * materialTypes;

@property (nonatomic,assign) NSInteger pageIndex;

@property (nonatomic,strong) UISearchBar * searchBar;

@end

@implementation ECMaterailTypeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择商品类别";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(rightClick:)];
    [self setUI];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.materialTypes.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    ECShopMaterialType * type = [self.materialTypes objectAtIndex:section];
    if (type.isSelected) {
        return type.children.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.contentView.backgroundColor = @"#F7FCF8".toColor;
        cell.textLabel.textColor = @"#333333".toColor;
    }
    ECShopMaterialType * type1 = [self.materialTypes objectAtIndex:indexPath.section];
    ECShopMaterialType * type2 = [type1.children objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"    %@",type2.MaterialTypeName];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ECMaterialTypeBigTypeHeaderView * view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    if (view == nil) {
        view = [[ECMaterialTypeBigTypeHeaderView alloc] initWithReuseIdentifier:@"header"];
        view.contentView.backgroundColor = [UIColor whiteColor];
        view.addButton.hidden = YES;
        view.delegate = self;
    }
    view.contentView.tag = section;
    ECShopMaterialType * type = [self.materialTypes objectAtIndex:section];
    if (type.isSelected) {
        view.imageView.highlighted = YES;
    }else{
        view.imageView.highlighted = NO;
    }
    view.nameLabel.text = type.MaterialTypeName;
    return view;
}

#pragma mark - ECMaterialTypeBigTypeHeaderViewDelegate
- (void)headerView:(ECMaterialTypeBigTypeHeaderView *)headerView section:(NSInteger)section{
    ECShopMaterialType * type = [self.materialTypes objectAtIndex:section];
    type.selected = !type.isSelected;
    [self.tableView reloadData];
}

#pragma mark - event
- (IBAction)rightClick:(id)sender{
    NSLog(@"%s",__FUNCTION__);
    ECMaterailTypeEditViewController * vc = [[ECMaterailTypeEditViewController alloc] init];
    vc.materialTypes = self.materialTypes;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - network
- (void)loadNewData{
    GLHTTPParam *param = [GLHTTPParam param];
    [param setSafeValue:@(1) forKey:@"page"];
    [param setSafeValue:@(200) forKey:@"limit"];
    [GLBaseHTTPTool getRequestURL:@"api/Material/GetTypePage" requestParam:param resultModelType:[ECShopMaterialTypeResult class] success:^(ECShopMaterialTypeResult * result) {
        if (result.code == 0) {
            //成功拉取到 商品类型数据
            [self adjustMaterialType:result.data];
            [self.tableView reloadData];
        }else{
            [MBProgressHUD showText:result.msg toView:self.view];
        }
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        [MBProgressHUD showText:@"数据拉取失败" toView:self.view];
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)adjustMaterialType:(NSArray *)array{
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    NSMutableArray *types = [NSMutableArray array];
    for (ECShopMaterialType * shopType in array) {
        if (shopType.PId.integerValue == 0) {
            [types addObject:shopType];
        }else{
            NSMutableArray * temp = [dict objectForKey:shopType.PId];
            if (temp == nil) {
                temp = [NSMutableArray array];
                [dict setObject:temp forKey:shopType.PId];
            }
            [temp addObject:shopType];
        }
    }
    for (ECShopMaterialType *shopType in types) {
        NSMutableArray * temp = [dict objectForKey:shopType.Id];
        shopType.children = temp;
    }
    self.materialTypes = types;
}

- (void)loadMoreData{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.26 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_footer endRefreshing];
    });
}


- (void)setUI{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 54)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.mas_equalTo(54);
    }];
    
    //搜索视图
    self.searchBar.layer.cornerRadius = 16;
    self.searchBar.clipsToBounds = YES;
    self.searchBar.layer.borderWidth = 1;
    self.searchBar.layer.borderColor = @"#cccccc".toColor.CGColor;
    [view addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(12*PX_RELATIVE375);
        make.top.offset(12);
        make.height.mas_equalTo(32);
        make.right.mas_offset(-5);
    }];
    //数据展示视图
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = @"#f4f4f4".toColor;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.and.bottom.offset(0);
        make.top.equalTo(view.mas_bottom);
    }];
}

#pragma mark - getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.00000001)];
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.00000001)];
        //        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorColor = @"#f4f4f4".toColor;
        _tableView.sectionHeaderHeight = 44;
        _tableView.sectionFooterHeight = 0.00001 * PX_RELATIVE375;
        _tableView.rowHeight = 44;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
//        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [UISearchBar new];
        [_searchBar setImage:[UIImage imageNamed:@"search_member"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        _searchBar.placeholder = @"搜索";
        [_searchBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]]];
        [_searchBar setPositionAdjustment:UIOffsetMake(-6, 0) forSearchBarIcon:UISearchBarIconSearch];
        for (UIView * v in _searchBar.subviews.firstObject.subviews) {
            if ([v isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                UITextField * tf = (UITextField*)v;
                tf.font = ECFONT(14);
            }
        }
    }
    return _searchBar;
}

@end
